package com.iiapk.gridnew.util;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;

import com.iiapk.gridnew.OAuthActivity;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.OAuthClient;

public class TokenStore {
	
	public static String fileName = "qq_token_store";
	public static final String URL_ACTIVITY_CALLBACK = "QWeibo4android://OAuthActivity";
	
	public static OAuth oauth;
	public static OAuthClient auth;
	
	public static void store(Context context,OAuth oauth) {
		SharedPreferences settings = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("oauth_token", oauth.getOauth_token());
		editor.putString("oauth_token_secret", oauth.getOauth_token_secret());	
		editor.commit();		
	}
	
	public static String[] fetch(Context context) {
		SharedPreferences settings = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
		String oauth_token = settings.getString("oauth_token", null);
		String oauth_token_secret = settings.getString("oauth_token_secret", null);
		return new String[] {oauth_token, oauth_token_secret};
	}
	
	public static void clear(Context context) {
		SharedPreferences settings = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.clear();  
        editor.commit(); 
	}	
	
	public static void get(Context context,String key,String secret){
		oauth = new OAuth(key,secret,URL_ACTIVITY_CALLBACK); 
		String[] oauth_token_array = TokenStore.fetch(context);
		String oauth_token = oauth_token_array[0];
		String oauth_token_secret = oauth_token_array[1];
		
		if (oauth_token != null && oauth_token_secret != null) { 
			Intent intent = new Intent(context, OAuthActivity.class);
			intent.putExtra("oauth_token", oauth_token);
			intent.putExtra("oauth_token_secret", oauth_token_secret);
			context.startActivity(intent);
		} else {
			try {
				auth = new OAuthClient();// OAuth 认证对象
				// 获取request token
				oauth = auth.requestToken(oauth);
				if (oauth.getStatus() == 1) {
					System.out.println("Get Request Token failed!");
					return;
				} else {
					String _oauth_token = oauth.getOauth_token();
					String url = "http://open.t.qq.com/cgi-bin/authorize?oauth_token="
							+ _oauth_token;
					Uri uri = Uri.parse(url);
					context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
